// 引入Vue核心库
import Vue from 'vue'
// 引入Vue的路由功能模块
import VueRouter from 'vue-router'

import MyLogin from '@/components/MyLogin.vue'
import MyHome from '@/components/MyHome.vue'

import MyUsers from '@/components/menus/MyUsers.vue'
import MyRights from '@/components/menus/MyRights.vue'
import MyGoods from '@/components/menus/MyGoods.vue'
import MyOrders from '@/components/menus/MyOrders.vue'
import MySettings from '@/components/menus/MySettings.vue'

import MyUserDetail from '@/components/user/MyUserDetail.vue'

// 导入路径数组模块，该模块包含了路由的相关路径信息
import pathArr from '@/router/pathArr.js'

// 安装VueRouter，使Vue能够使用路由功能
Vue.use(VueRouter)

// 创建一个新的VueRouter实例
const router = new VueRouter(
  {
    routes: [
      // 第一个路由规则：当路径为'/'时，重定向到'/login'
      { path: '/', redirect: '/login' },
      // 第二个路由规则：当路径为'/login'时，显示MyLogin组件
      { path: '/login', component: MyLogin },
      {
        path: '/home',
        component: MyHome,
        redirect: '/home/users',
        children: [
          { path: 'users', component: MyUsers },
          { path: 'rights', component: MyRights },
          { path: 'goods', component: MyGoods },
          { path: 'orders', component: MyOrders },
          { path: 'settings', component: MySettings },
          // 用户详情页
          { path: 'userinfo/:id', component: MyUserDetail, props: true }
        ]
      }
    ]
  }
)

// 【全局前置守卫】在每个路由变更之前执行的钩子函数
router.beforeEach((to, from, next) => {
  // 判断即将跳转的路径是否存在于pathArr数组中
  if (pathArr.indexOf(to.path) !== -1) {
    const token = localStorage.getItem('token')
    // 如果已存在token，允许访问
    if (token) {
      next()
    } else {
      // 如果不存在token，重定向到登录页面
      next('/login')
    }
  } else {
    next()
  }
})

// 导出VueRouter实例，以便在其他Vue组件中使用
export default router